﻿Imports DocumentFormat.OpenXml.Wordprocessing
Imports Ingr.RAD2D
Imports Llama
Imports Telerik.WinControls.UI

Public Class Result
    Dim dsResult As DataSet '用于在result.vb里 

    Sub New(ByRef _dsResult As DataSet)

        ' 此调用是设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        dsResult = _dsResult

    End Sub
    Private Sub RadGridView_Click(sender As Object, e As EventArgs) Handles RadGridView.Click

    End Sub

    Private Sub Result_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.RadDropDownList1.Items.Clear()

        'For index = 0 To CheckFuncListChecked.Count - 1
        '    If CheckFuncListChecked(index) = func_CheckDrawingProp Then
        '        ' "图面属性_" 
        '        For I = 0 To dsOutput.Tables.Count - 1
        '            If dsOutput.Tables(I).TableName.StartsWith("图面属性_") Then
        '                Me.RadDropDownList1.Items.Add(dsOutput.Tables(I).TableName)
        '            End If
        '        Next
        '    Else
        '        Me.RadDropDownList1.Items.Add(CheckFuncListChecked(index))
        '    End If

        'Next
        Me.RadDropDownList1.Items.Add("冗余断点")
        Me.RadGridView.AllowAddNewRow = False
        Me.RadGridView.AllowDeleteRow = False
        Me.RadGridView.AllowEditRow = False
        Me.RadGridView.MultiSelect = False
        Me.RadGridView.AutoSizeColumnsMode = GridViewAutoSizeColumnsMode.Fill
        Me.RadGridView.SelectionMode = GridViewSelectionMode.FullRowSelect
        AddHandler Me.RadGridView.CellFormatting, AddressOf RadGridView_CellFormatting
    End Sub
    '调大单元格字体
    Private Sub RadGridView_CellFormatting(sender As Object, e As Telerik.WinControls.UI.CellFormattingEventArgs) Handles RadGridView.CellFormatting
        Dim newFont As New System.Drawing.Font(New System.Drawing.FontFamily("Calibri"), 12.0F, FontStyle.Regular)
        e.CellElement.Font = newFont
    End Sub



    Private Sub SPPID图上定位_Click(sender As Object, e As EventArgs) Handles SPPID图上定位.Click
        If Me.RadGridView.SelectedRows.Count = 1 Then
            Dim selectitem = Me.RadGridView.SelectedRows(0)
            Dim COL_ID = Me.RadGridView.Columns.GetColumnByFieldName("ID")
            Dim COL_DWGNAME = Me.RadGridView.Columns.GetColumnByFieldName("所在图纸")

            If IsNothing(COL_ID) Or IsNothing(COL_DWGNAME) Then
                Exit Sub
            End If
            If COL_ID.Length = 0 Or COL_DWGNAME.Length = 0 Then
                Exit Sub
            End If

            Dim SPID = selectitem.Cells("ID").Value
            Dim DWGName = selectitem.Cells("所在图纸").Value
            Dim DWGID As String = ""

            Try


                ' initialize the PID Object Manager
                'Dim activProj As LMActiveProject
                'activProj = ds.GetActiveProject()
                'Dim plitem As LMPlantItem
                'plitem = ds.GetPlantItem(SPID.ToString)
                Dim radApp As Interop.RAD2D.Application
                Dim pidAutoApp As InteropPidAuto.Application

                'pidAutoApp = CreateObject("PIDAutomation.Application")

                pidAutoApp = New InteropPidAuto.Application()

                pidAutoApp.Activate()

                radApp = GetObject(, "SmartPlantPID.Application").radapplication
                Dim dtRep As New DataTable
                Dim Sql = $"select sp_id from xxxSchemaName.t_drawing t where t.name='{DWGName}'"
                MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, Sql, dtRep)

                Dim curDrawing As InteropPidAuto.Drawing


                If dtRep.Rows.Count > 0 Then ' And pidAutoApp.ActiveDrawing.Name.Replace(".pid", "") = DWGName Then
                    Dim found = False
                    For Each openDwg As InteropPidAuto.Drawing In pidAutoApp.Drawings
                        If openDwg.Name.Replace(".pid", "") = DWGName Then
                            openDwg.Activate()
                            curDrawing = pidAutoApp.ActiveDrawing
                            found = True
                        End If
                    Next
                    'For Each openDwg As Interop.RAD2D.Document In radApp.Documents
                    '    If openDwg.Name.Replace(".pid", "") = DWGName Then
                    '        openDwg.Activate()
                    '        found = True
                    '    End If
                    'Next
                    If Not found Then
                        curDrawing = pidAutoApp.Drawings.OpenDrawing(DWGName)
                        'MessageBox.Show($"请在P&ID中，事先打开{DWGName}该图纸")
                        'Exit Sub
                    End If
                    DWGID = dtRep.Rows(0)(0).ToString

                    Sql = $"select graphicoid from xxxSchemaName.t_Representation t where t.sp_modelitemid='{SPID}' and t.sp_drawingid='{DWGID}'"
                    dtRep.Reset()
                    MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, Sql, dtRep)

                    If dtRep.Rows.Count = 0 Then '分支点的话,id可能本来就不是modelitem
                        dtRep.Reset()
                        Sql = $"select graphicoid from xxxSchemaName.t_Representation t where t.sp_id='{SPID}'"
                        MyPIDConn.PIDReadDataByDBA(MyPIDConn.PIDPlant_DBNAME, MyPIDConn.ActivePlantPIDApp_User, Sql, dtRep)
                    End If

                    If dtRep.Rows.Count > 0 Then

                        '' deselect anything the user may have selected, this will ensure we "fit" nothing but the drawing view
                        '' comment out the following line, if you just want to Fit to the active Select Set
                        pidAutoApp.ActiveSelectSet.RemoveAll()
                        Debug.Print(radApp.ActiveDocument.ActiveSheet.Name)
                        pidAutoApp.ActiveSelectSet.Add(radApp.ActiveDocument.ActiveSheet.DrawingObjects("Symbol2d " & dtRep.Rows(0)(0).ToString)) ' WORKS !!!  plitem.AsLMModelItem.Representations.Nth(1)


                        'Debug.Print(radApp.ActiveDocument.ActiveSheet.Name)
                        pidAutoApp.ActiveSelectSet.Add(radApp.ActiveDocument.ActiveSheet.DrawingObjects("Symbol2d " & dtRep.Rows(0)(0).ToString)) ' WORKS !!!  plitem.AsLMModelItem.Representations.Nth(1)



                        ' for Fit view to Select Set, there are a couple of options...
                        Dim intOption As Integer
                        intOption = 2
                        Select Case (intOption)
                            Case 1 ' WORKS, but uses a hard-coded path to a command macro
                                ' the radApp object also has the RunMacro method...
                                pidAutoApp.RunMacro("C:\Program Files (x86)\SmartPlant\P&ID Workstation\Bin\PidViewCmds.dll")
                            Case 2 ' WORKS, in SPPID 2014...
                                radApp.RunCommand(40068)
                        End Select
                    End If
                Else

                End If
            Catch ex As Exception

            End Try
            ' clean up object variables
        End If
    End Sub

    ''' <summary>
    ''' 根据pid数据库里的OID，找到ssk里的对象
    ''' </summary>
    ''' <param name="radApp"></param>
    ''' <param name="rep"></param>
    ''' <returns></returns>
    Private Function GetRadGraphic(radApp As Interop.RAD2D.Application, rep As LMRepresentation) As Object  ' 
        ' "xxx " gets replaced by RAD/SmartSketch object type, like "Symbol2d "; GraphicOID is the RAD object's Key value
        GetRadGraphic = radApp.ActiveDocument.ActiveSheet.DrawingObjects("Symbol2d " & rep.Attributes("GraphicOID").Value) '
    End Function

    Private Sub RadDropDownList1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles RadDropDownList1.SelectedIndexChanged
        'Me.RadDropDownList1.Items.Add(dsOutput.Tables(I).TableName)
        Dim tbName = Me.RadDropDownList1.SelectedItem

        Me.RadGridView.DataSource = Nothing
        If dsResult.Tables.Contains(tbName) Then
            Me.RadGridView.DataSource = dsResult.Tables(tbName)
            '隐藏‘ID’
            Dim targetColumnName As String = "ID"
            Dim targetColumn As GridViewDataColumn = Me.RadGridView.Columns.FirstOrDefault(Function(col) col.Name = targetColumnName)
            If targetColumn IsNot Nothing Then
                targetColumn.IsVisible = False
            End If
            '将’备注‘列移动到最右边
            Dim columnIndexTomove As Integer = 3
            If columnIndexTomove >= 0 AndAlso columnIndexTomove < Me.RadGridView.Columns.Count Then
                Dim columnTomove As GridViewColumn = Me.RadGridView.Columns(columnIndexTomove)
                Me.RadGridView.Columns.Remove(columnTomove)
                Me.RadGridView.Columns.Insert(Me.RadGridView.Columns.Count, columnTomove)
            End If
        End If

    End Sub
End Class